package org.lds.message.center.server.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.lds.message.center.common.enums.ErrorEnum;
import org.lds.message.center.common.exception.BusinessException;
import org.lds.message.center.common.exception.ExceptionMessage;
import org.lds.message.center.common.model.ResultDTO;
import org.lds.message.center.service.grpc.GrpcResultDTO;

@Slf4j
public class GrpcResultDTOUtil {

    public static GrpcResultDTO toGrpc(ResultDTO<Boolean> resultDTO) {
        GrpcResultDTO.Builder builder = GrpcResultDTO.newBuilder();
        if (StringUtils.isNotEmpty(resultDTO.getCode())) {
            builder.setCode(resultDTO.getCode());
        }
        if (StringUtils.isNotEmpty(resultDTO.getMessage())) {
            builder.setMessage(resultDTO.getMessage());
        }
        builder.setSuccess(resultDTO.isSuccess());
        return builder.build();
    }

    public static ExceptionMessage errorMessage(Exception e) {
        if (e instanceof BusinessException) {
            return ((BusinessException) e).getExceptionMessage();
        }

        log.error("errorMessage. cause={}", e);
        ErrorEnum errorEnum = ErrorEnum.SYSTEM_ERROR;
        return new ExceptionMessage(errorEnum.getErrCode(), errorEnum.getErrMsg());
    }

}
